package controller.user_management;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.trek2000.android.enterprise.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import adapter.company.SelectCompanyAdapter;
import adapter.group_management.AddMemberToGroupAdapter;
import adapter.user_management.AllTabInUserManagementFragmentAdapter;
import adapter.user_management.CompanyManagerTabInUserManagementFragmentAdapter;
import adapter.user_management.GeneralUserTabInUserManagementFragmentAdapter;
import adapter.user_management.GroupManagerTabInUserManagementFragmentAdapter;
import define.API;
import define.Key;
import model.company.SelectCompanyItem;
import model.user_management.AllTabInUserManagementItem;
import ui.fragment.company.SelectCompanyFragment;
import ui.fragment.group_management.AddMemberToGroupFragment;
import ui.fragment.user_management.AllTabInUserManagementFragment;
import ui.fragment.user_management.CompanyManagerTabInUserManagementFragment;
import ui.fragment.user_management.GeneralUserTabInUserManagementFragment;
import ui.fragment.user_management.GroupManagerTabInUserManagementFragment;
import utils.Utils;

/**
 * Created by trek2000 on 19/8/2014.
 */
public class AllTabInUserManagementFragmentAsync extends AsyncTask<String, Void, Boolean> {

    /**
     * String section
     */
    private String FIRST_NAME = "";
    private String LAST_NAME = "";
    private String EMAIL = "";
    private String CAMERA_MODEL = "";
    private String JOURNALIST_ID = "";
    private String ORGANIZATION = "";
    private String MAC = "";
    private int gender = 0;
    private String ROLE = "";
    private String ADDED_TIME_LOCAL = "";
    private int number_of_photos = 0;
    private int number_of_videos = 0;
    private String LAST_ACTIVITY = "";
    private long user_global_id = 0;
    private long user_company_id = 0;
    private String USER_EMAIL = "";
    private String AVATAR = "";
    private String USER_STATUS = "";

    private String ERROR = "";
    private String STATUS = "";

    /**
     * View section
     */

    /**
     * The others section
     */
    private Context mContext;
    public static ArrayList <AllTabInUserManagementItem> mAlAllTabInUserManagement = new ArrayList<>();
    public static ArrayList <AllTabInUserManagementItem> mAlCompanyManagerTabInUserManagement = new ArrayList<>();
    public static ArrayList <AllTabInUserManagementItem> mAlGroupManagerTabInUserManagement = new ArrayList<>();
    public static ArrayList <AllTabInUserManagementItem> mAlGeneralUserTabInUserManagement = new ArrayList<>();
    public static ArrayList <Long> mAlCompanyId = new ArrayList<>();

    public AllTabInUserManagementFragmentAsync(Context context) {
        this.mContext = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        return getData(params);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //TODO clear, check id unique later
        if (!mAlAllTabInUserManagement.isEmpty()) {
            mAlAllTabInUserManagement.clear();
        }
        if (!mAlCompanyManagerTabInUserManagement.isEmpty()) {
            mAlCompanyManagerTabInUserManagement.clear();
        }
        if (!mAlGroupManagerTabInUserManagement.isEmpty()) {
            mAlGroupManagerTabInUserManagement.clear();
        }
        if (!mAlGeneralUserTabInUserManagement.isEmpty()) {
            mAlGeneralUserTabInUserManagement.clear();
        }
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        // hide waiting dialog
        Utils.hideWaitingDialog();

        if (!result) {
            Toast.makeText(mContext, ERROR ,
                    Toast.LENGTH_SHORT).show();
            //enable ibtn back, avoid not load view in create group fragment, if user click back so fast.
            if (AddMemberToGroupFragment.mIbtnBackInAddMemberToGroupFragment != null)
                AddMemberToGroupFragment.mIbtnBackInAddMemberToGroupFragment.setEnabled(true);
        } else {
            //add member to group fragment
            if (AddMemberToGroupFragment.addMemberToGroupAdapter != null &&
                    AddMemberToGroupFragment.mLsInAddMemberToGroupFragment !=null ) {
                AddMemberToGroupFragment.addMemberToGroupAdapter = new AddMemberToGroupAdapter(
                        mContext, R.layout.simple_list_item_in_add_member_to_group_fragment,
                        mAlAllTabInUserManagement,
                        AddMemberToGroupFragment.IS_ADD_GROUP_MANAGER);
                AddMemberToGroupFragment.mLsInAddMemberToGroupFragment.setAdapter(AddMemberToGroupFragment.addMemberToGroupAdapter);
            }
            // all tab in user management
            if(AllTabInUserManagementFragment.allTabInUserManagementFragmentAdapter != null &&
                    AllTabInUserManagementFragment.mLvInAllTabInUserManagementFragment != null) {
                AllTabInUserManagementFragment.allTabInUserManagementFragmentAdapter = new AllTabInUserManagementFragmentAdapter(
                        mContext, R.layout.simple_list_item_in_all_tab_in_user_management_fragment,
                        mAlAllTabInUserManagement
                );
                AllTabInUserManagementFragment.mLvInAllTabInUserManagementFragment.setAdapter(
                        AllTabInUserManagementFragment.allTabInUserManagementFragmentAdapter
                );
            }
            // company manager tab in user management
            if(CompanyManagerTabInUserManagementFragment.companyManagerTabInUserManagementFragmentAdapter != null &&
                    CompanyManagerTabInUserManagementFragment.mLvInCompanyManagerTabInUserManagementFragment != null) {
                CompanyManagerTabInUserManagementFragment.companyManagerTabInUserManagementFragmentAdapter = new CompanyManagerTabInUserManagementFragmentAdapter(
                        mContext,
                        R.layout.simple_list_item_in_company_manager_tab_in_user_management_fragment,
                        mAlCompanyManagerTabInUserManagement);
                CompanyManagerTabInUserManagementFragment.mLvInCompanyManagerTabInUserManagementFragment.setAdapter(
                        CompanyManagerTabInUserManagementFragment.companyManagerTabInUserManagementFragmentAdapter);
            }
            //group manager tab in user management
            if(GroupManagerTabInUserManagementFragment.groupManagerTabInUserManagementFragmentAdapter != null &&
                    GroupManagerTabInUserManagementFragment.groupManagerTabInUserManagementFragmentAdapter != null) {
                GroupManagerTabInUserManagementFragment.groupManagerTabInUserManagementFragmentAdapter = new GroupManagerTabInUserManagementFragmentAdapter(
                        mContext,
                        R.layout.simple_list_item_in_group_manager_tab_in_user_management_fragment,
                        mAlGroupManagerTabInUserManagement);
                GroupManagerTabInUserManagementFragment.mLvInGroupManagerTabInUserManagementFragment.setAdapter(
                        GroupManagerTabInUserManagementFragment.groupManagerTabInUserManagementFragmentAdapter);
            }
            //general user tab in user management
            if(GeneralUserTabInUserManagementFragment.generalUserTabInUserManagementFragmentAdapter != null &&
                    GeneralUserTabInUserManagementFragment.generalUserTabInUserManagementFragmentAdapter != null) {
                GeneralUserTabInUserManagementFragment.generalUserTabInUserManagementFragmentAdapter = new GeneralUserTabInUserManagementFragmentAdapter(
                        mContext,
                        R.layout.simple_list_item_in_general_user_tab_in_user_management_fragment,
                        mAlGeneralUserTabInUserManagement);
                GeneralUserTabInUserManagementFragment.mLvInGeneralUserTabInUserManagementFragment.setAdapter(
                        GeneralUserTabInUserManagementFragment.generalUserTabInUserManagementFragmentAdapter);
            }
            //enable ibtn back, avoid not load view in create group fragment, if user click back so fast.
            if (AddMemberToGroupFragment.mIbtnBackInAddMemberToGroupFragment != null)
                AddMemberToGroupFragment.mIbtnBackInAddMemberToGroupFragment.setEnabled(true);
        }
    }

    /**
     * Basic methods
     */
    private boolean getData(String[] params) {
        HttpPost mHttpPost = new HttpPost(API.GET_USER_LIST_IN_COMPANY);
        List<NameValuePair> mListValues = new ArrayList<NameValuePair>();
        /**
         * user_Name
         * password
         * device_token
         * device_OS
         */
        mListValues.add(new BasicNameValuePair(Key.USER_GLOBAL_ID, params[0]));
        mListValues.add(new BasicNameValuePair(Key.ACCESS_TOKEN, params[1]));
        mListValues.add(new BasicNameValuePair(Key.COMPANY_ID, params[2]));
        mListValues.add(new BasicNameValuePair(Key.COMPANY_ID_GROUP, params[3]));

        try {
            mHttpPost.setEntity(new UrlEncodedFormEntity(mListValues));
            HttpParams mHttpParams = new BasicHttpParams();

            int TIMEOUT_CONNECTION = 30000;
            int TIMEOUT_SOCKET = 30000;

            HttpConnectionParams.setConnectionTimeout(
                    mHttpParams, TIMEOUT_CONNECTION);
            HttpConnectionParams.setSoTimeout(mHttpParams, TIMEOUT_SOCKET);
            HttpClient mHttpclient = new DefaultHttpClient(mHttpParams);
            HttpResponse mHttpResponse;
            mHttpResponse = mHttpclient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            String XML = EntityUtils.toString(mHttpEntity);

            Log.i("", AllTabInUserManagementFragmentAsync.class.getSimpleName() + " " + XML);

            JSONObject mJoXml = new JSONObject(XML);
            //get string in mJoXml
            STATUS = mJoXml.getString(Key.STATUS);
            if (STATUS.equals(mContext.getString(R.string.success_))) {
                //get mJaUsers in mJoXml
                JSONArray mJaUsers = mJoXml.getJSONArray(Key.USERS);
                if (!"[]".equals(mJaUsers.toString())) {
                    for (int i = 0; i <mJaUsers.length(); i++) {
                        //get mJoCompanies in mJaCompanies
                        JSONObject mJoUsers = mJaUsers.getJSONObject(i);
                        //get string in mJoCompanies
                        FIRST_NAME = mJoUsers.getString(Key.FIRSTNAME);
                        LAST_NAME = mJoUsers.getString(Key.LASTNAME);
                        EMAIL = mJoUsers.getString(Key.EMAIL);
                        CAMERA_MODEL = mJoUsers.getString(Key.CAMERA_MODEL);
                        JOURNALIST_ID = mJoUsers.getString(Key.JOURNALIST_ID);
                        ORGANIZATION = mJoUsers.getString(Key.ORGANIZATION);
                        MAC = mJoUsers.getString(Key.MAC);
                        gender = mJoUsers.getInt(Key.GENDER);
                        ROLE = mJoUsers.getString(Key.ROLE);
                        ADDED_TIME_LOCAL = mJoUsers.getString(Key.ADDEDTIME_LOCAL);
                        number_of_photos = mJoUsers.getInt(Key.NUMBER_OF_PHOTOS);
                        number_of_videos = mJoUsers.getInt(Key.NUMBER_OF_VIDEOS);
                        LAST_ACTIVITY = mJoUsers.getString(Key.LASTACTIVITY);
                        user_global_id = mJoUsers.getInt(Key.USER_GLOBAL_ID);
                        user_company_id = mJoUsers.getInt(Key.USER_COMPANY_ID);
                        USER_EMAIL = mJoUsers.getString(Key.USER_EMAIL);
                        AVATAR = mJoUsers.getString(Key.AVATAR);
                        USER_STATUS = mJoUsers.getString(Key.USER_STATUS);
                        AllTabInUserManagementItem allTabInUserManagementItem = new AllTabInUserManagementItem(
                                FIRST_NAME, LAST_NAME, EMAIL,
                                CAMERA_MODEL, JOURNALIST_ID, ORGANIZATION,
                                MAC, gender, ROLE,
                                ADDED_TIME_LOCAL, number_of_photos, number_of_videos,
                                LAST_ACTIVITY, user_global_id, user_company_id,
                                USER_EMAIL, AVATAR, USER_STATUS
                        );
                        //TODO check duplicate at here
                        // all users
                        mAlAllTabInUserManagement.add(allTabInUserManagementItem);
                        if (mContext.getString(R.string.company_manager_).equals(ROLE)) {
                            //company manager
                            mAlCompanyManagerTabInUserManagement.add(allTabInUserManagementItem);
                        } else if (mContext.getString(R.string.group_managemer_).equals(ROLE)) {
                            // group manager
                            mAlGroupManagerTabInUserManagement.add(allTabInUserManagementItem);
                        } else if (mContext.getString(R.string.general_user_).equals(ROLE)) {
                            // general user
                            mAlGeneralUserTabInUserManagement.add(allTabInUserManagementItem);
                        }

                    }
                }
                return  true;
            } else if (STATUS.equals(mContext.getString(R.string.error))) {
                ERROR = mJoXml.getString(Key.ERROR);
                return false;
            }
        } catch (ClassCastException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}